﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using IGM.DataProvider;
using IGM.Framework.Commons;
using IGM.Framework.Constants;

namespace IGM.Presentation.Management
{
    public partial class InternManagementControl : UserControl
    {
        private readonly Business.Business _business;
        private int _groups;
        private int _members;
        private int _blance;
        private List<StudentMark> _students;
        public InternManagementControl()
        {
            InitializeComponent();
            _business = Main.Main.Instance.IgmBusiness;
        }

        private void InternManagementControlLoad(object sender, EventArgs e)
        {
            LoadMajor();
            LoadKindIntern();
            LoadLecturer();
            LoadGroup();
            Dock = DockStyle.Top;
        }

        private void LoadMajor()
        {
            cboMajors.DataSource = _business.GetListMajor();
            cboMajors.DisplayMember = PropertiesConstants.Name;
            cboMajors.ValueMember = PropertiesConstants.Id;
        }

        private void LoadKindIntern()
        {
            cboKindInterns.DataSource = _business.GetListKindIntern();
            cboKindInterns.DisplayMember = PropertiesConstants.Name;
            cboKindInterns.ValueMember = PropertiesConstants.Id;
        }

        private void LoadLecturer()
        {
            cboLecturers.DataSource = _business.GetListLecturerByMajorId(Convert.ToInt32(((Major)cboMajors.SelectedItem).Id));
            cboLecturers.DisplayMember = PropertiesConstants.Name;
            cboLecturers.ValueMember = PropertiesConstants.Id;
        }

        /// <summary>
        /// If kindinter = 3 (Graduation) then kindmark = 2, condition = 7; else kindmark = 1, condition = 0 (Intern)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void CboKindInternsSelectedIndexChanged(object sender, EventArgs e)
        {
            var kindintern = Convert.ToInt32(((KindIntern)cboKindInterns.SelectedItem).Id);
            var major = Convert.ToInt32(((Major)cboMajors.SelectedItem).Id);
            if (kindintern != 3)
            {
                _students = _business.GetStudentQualityIntern(major, 1, 0);
                txtCountStudents.Text = _students.Count.ToString();
                LoadGroup();
            }
            else
            {
                //xoa control cu
                Controls.Clear();          
                // Khoi tao control moi
                var graduationManagement = new GraduationManagementControl();
                Controls.Add(graduationManagement);
            }
        }

        #region -- CONDITION GROUP--

        /// <summary>
        /// Codition
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PtbConditionClick(object sender, EventArgs e)
        {
            pnlResult.Visible = true;
            MessageBox.Show("Thêm nhóm");
            var total = Convert.ToInt32(txtCountStudents.Text.Trim());

            if (total < Convert.ToInt32(nupNumberGroup.Value) || total < Convert.ToInt32(cboNumberMembers.SelectedItem))
            {
                MessageBox.Show(string.Format(ConstantMessages.NotValidData, "số sinh viên", "nhóm hoặc số thành viên trong mỗi nhóm"));
            }

            if (Equals(nupNumberGroup.Visible, true))
            {
                _groups = Convert.ToInt32(nupNumberGroup.Value);
                _members = total / _groups;
            }
            else
            {
                _members = Convert.ToInt32(cboNumberMembers.SelectedItem);
                _groups = total / _members;
            }
            _blance = total % _groups;
            txtNumberGExpected.Text = _groups.ToString();
            txtNumberMExpected.Text = _members.ToString();
            txtBlance.Text = _blance.ToString();
        }

        /// <summary>
        /// Show solution
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void LblOrClick(object sender, EventArgs e)
        {
            if (cboNumberMembers.Visible == false)
            {
                cboNumberMembers.Visible = true;
                nupNumberGroup.Visible = false;
            }
            else
            {
                cboNumberMembers.Visible = false;
                nupNumberGroup.Visible = true;
            }
        }

        /// <summary>
        /// Add a new group
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnAddAGroupClick(object sender, EventArgs e)
        {
            txtGroupOfficial.Text = txtMemberOfficial.Text = txtGroupBlance.Text = txtMemberBlance.Text = string.Empty;
            btnKeepGroup.Visible = false;

            if (_blance == 0)
            {
                MessageBox.Show(@"Không dư thành viên nào nên không thể thêm nhóm mới");
                txtGroupBlance.Text = txtMemberBlance.Text = string.Empty;
            }
            else 
            {
                _groups = _groups + 1;
                txtGroupBlance.Text = 1.ToString();
                txtMemberBlance.Text = _blance.ToString();   
            }

                txtGroupOfficial.Text = _groups.ToString();
                txtMemberOfficial.Text = _members.ToString();
                      
        }

        /// <summary>
        /// Keep number of groups
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void BtnKeepGroupClick(object sender, EventArgs e)
        {
            txtGroupOfficial.Text = txtMemberOfficial.Text = txtGroupBlance.Text = txtMemberBlance.Text = string.Empty;
            btnAddAGroup.Visible = true;

            if (_blance == 0)
            {
                MessageBox.Show(@"Không dư thành viên nào nên không thể thêm nhóm mới");
                txtGroupBlance.Text = txtMemberBlance.Text = string.Empty;

            }
            else 
            {
                _groups = _groups - _blance;
                txtGroupBlance.Text = _blance.ToString();
                txtMemberBlance.Text = (_members + 1).ToString();
            }

            txtGroupOfficial.Text = _groups.ToString();
            txtMemberOfficial.Text = _members.ToString();
        
        }

        private void PicShowGroupClick(object sender, EventArgs e)
        {
            // Delete old data
            _business.ClearOldData(Convert.ToInt32(((KindIntern)cboKindInterns.SelectedItem).Id));

            // Insert new data
            try
            {
                var groups = new List<Group>();
                var groupBalance = Convert.ToInt32(txtGroupBlance.Text.Trim());
                var memberBalance = Convert.ToInt32(txtMemberBlance.Text.Trim());

                for (var i = 0; i < groupBalance; i++)
                {
                    groups.Add(new Group
                    {
                        Name = string.Format("Nhóm {0}", i + 1),
                        IdKindIntern = Convert.ToInt32(((KindIntern)cboKindInterns.SelectedItem).Id),
                        IdMajor = Convert.ToInt32(((Major)cboMajors.SelectedItem).Id),
                        NumberMembers = memberBalance,
                        Project = string.Format("Chưa có")
                    });
                }

                var og = Convert.ToInt32(txtGroupOfficial.Text.Trim());
                var om = Convert.ToInt32(txtMemberOfficial.Text.Trim());
                for (var i = 0; i < og; i++)
                {
                    groups.Add(new Group
                    {
                        Name = string.Format("Nhóm {0}", i + 1 + groupBalance),
                        IdKindIntern = Convert.ToInt32(((KindIntern)cboKindInterns.SelectedItem).Id),
                        IdMajor = Convert.ToInt32(((Major)cboMajors.SelectedItem).Id),
                        NumberMembers = om,
                        Project = string.Format("Chưa có")
                    });
                }

                if (groups.Count < 1)
                {
                    MessageBox.Show(ConstantMessages.NoSelected, FileConstants.ProgramName);
                    return;
                }

                _business.AddGroup(groups);

                // Auto Add Group Lecturer
                _business.AutoAddGroupLecturer(groups);

                // Load group
                dgvGroupList.DataSource = _business.GetListGroupByKindInternId(((KindIntern)cboKindInterns.SelectedItem).Id, ((Major)cboMajors.SelectedItem).Id);

                ChooseMember();

                LoadGroup();
            }
            catch (Exception ex)
            {
                Logger.Write(null, ex);
            }
        }       

        #endregion

        #region -- GROUP --

        private void LoadGroup()
        {
            dgvGroupList.DataSource = _business.GetListGroupByKindInternId(((KindIntern)cboKindInterns.SelectedItem).Id, ((Major)cboMajors.SelectedItem).Id);
            DataGridViewHelper.ShowHideColumns(dgvGroupList,
                                               new[] { PropertiesConstants.IsChecked, PropertiesConstants.Name, "NumberMembers", "Project", "GroupLecturers"});
            DataGridViewHelper.ShowIsCheck(dgvGroupList);
            DataGridViewHelper.ApplyCheckedAllOrUncheckAll(dgvGroupList, false);
            DataGridViewHelper.ChangeDgvHeaderText(dgvGroupList, new[] { "IsChecked", "Name", "NumberMembers", "Project", "GroupLecturers"},
                                                   new[] { "Chọn", "Tên nhóm", "Số lượng thành viên", "Dự án", "Giáo viên hướng dẫn"});
            GroupCurrentRowChanged();
        }

        private void GroupCurrentRowChanged()
        {
            if (dgvGroupList.CurrentRow != null)
            {
                txtGroupName.Text = dgvGroupList.CurrentRow.Cells["Name"].Value.ToString();
                txtNumberMember.Text = dgvGroupList.CurrentRow.Cells["NumberMembers"].Value.ToString();
                txtProject.Text = dgvGroupList.CurrentRow.Cells["Project"].Value.ToString();
                lblGroupStudent.Text = string.Format(ConstantMessages.LblGroupStudent, txtGroupName.Text);

               LoadGroupStudents();
            }

            else
            {
                txtGroupName.Text = txtNumberMember.Text = string.Empty;
                ckbAllGroups.Checked = false;
            }
        }       

        private void DgvGroupListCellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvGroupList == null ||
               dgvGroupList.Columns[(string)typeof(Group).Properties().IsChecked] == null ||
               dgvGroupList.Columns[(string)typeof(Group).Properties().IsChecked].Index != e.ColumnIndex)
                return;

            dgvGroupList[e.ColumnIndex, e.RowIndex].Value =
                !(bool)dgvGroupList[e.ColumnIndex, e.RowIndex].Value;

            ckbAllGroups.Checked = DataGridViewHelper.AllRowsIsCheck(dgvGroupList);
        }

        private void DgvGroupListCurrentCellChanged(object sender, EventArgs e)
        {
            GroupCurrentRowChanged();
        }

        private void CkbAllGroupsCheckedChanged(object sender, EventArgs e)
        {
            DataGridViewHelper.ApplyCheckedAllOrUncheckAll(dgvGroupList, ckbAllGroups.Checked);
        }

        private void ReloadGroup(Group group)
        {
            LoadGroup();
            DataGridViewHelper.SetDgvCurrentCell(dgvGroupList, group.Name);
            GroupCurrentRowChanged();
        }

        private void BtnAddGroupsClick(object sender, EventArgs e)
        {
            try
            {
                var group = new Group
                {
                    Name = txtGroupName.Text.Trim(),
                    IdKindIntern = Convert.ToInt32(((KindIntern)cboKindInterns.SelectedItem).Id),
                    IdMajor = Convert.ToInt32(((Major)cboMajors.SelectedItem).Id),
                    NumberMembers = Convert.ToInt32(txtNumberMember.Text.Trim()),
                    Project = string.Format("Chưa có")
                };

                string message;

                if (_business.AddGroupValidator(group, out message))
                {
                    _business.AddGroup(group);

                    ReloadGroup(group);
                }
                else
                    MessageBox.Show(message);

            }
            catch (Exception ex)
            {
                Logger.Write(null, ex);
            }
        }

        private void BtnDeleteGroupsClick(object sender, EventArgs e)
        {
            try
            {
                var groups = new List<Group>();
                string message;

                for (var i = 0; i < dgvGroupList.RowCount; i++)
                {
                    if (!(bool)dgvGroupList[(string)typeof(Group).Properties().IsChecked, i].Value) continue;

                    groups.Add(new Group
                    {
                        Id = (int)dgvGroupList[(string)typeof(Group).Properties().Id, i].Value,
                        Name = dgvGroupList[(string)typeof(Group).Properties().Name, i].Value.ToString(),
                        IdKindIntern = Convert.ToInt32(dgvGroupList["IdKindIntern", i].Value),
                        IdMajor = Convert.ToInt32(((Major)cboMajors.SelectedItem).Id),
                        NumberMembers = Convert.ToInt32(dgvGroupList["NumberMembers", i].Value),
                        Project = dgvGroupList["Project", i].Value.ToString()
                    });
                }
                if (groups.Count < 1)
                {
                    MessageBox.Show(ConstantMessages.NoSelected, FileConstants.ProgramName);
                    return;
                }

                if (_business.DeleteGroupsValidator(groups, out message))
                {
                    if (MessageBox.Show(string.Format(ConstantMessages.ConfirmDeleteItem, " các nhóm đã chọn"), FileConstants.ProgramName, MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        _business.DeleteGroups(groups);
                        ReloadGroup(null);
                    }
                }
                else MessageBox.Show(message);
            }
            catch (Exception ex)
            {
                Logger.Write(null, ex);
            }
        }

        private void BtnEditGroupsClick(object sender, EventArgs e)
        {
            try
            {
                if (dgvGroupList.CurrentRow != null)
                {
                    var group = new Group
                    {
                        Id = Convert.ToInt32(dgvGroupList.CurrentRow.Cells[PropertiesConstants.Id].Value),
                        Name = txtGroupName.Text.Trim(),
                        IdKindIntern = Convert.ToInt32(((KindIntern)cboKindInterns.SelectedItem).Id),
                        IdMajor = Convert.ToInt32(((Major)cboMajors.SelectedItem).Id),
                        NumberMembers = Convert.ToInt32(txtNumberMember.Text.Trim()),
                        Project = txtProject.Text.Trim()
                    };
                    string message;
                    if (_business.EditGroupValidator(group, out message))
                    {
                        if (!_business.EditGroup(group))
                        {
                            MessageBox.Show(ConstantMessages.SaveItemNotSuccess, FileConstants.ProgramName);
                            return;
                        }
                        ReloadGroup(group);
                    }
                    else
                        MessageBox.Show(message);
                }
                else
                    MessageBox.Show(ConstantMessages.NoSelected, FileConstants.ProgramName);
            }

            catch (Exception ex)
            {
                Logger.Write(null, ex);
            }
        }

        #endregion

        #region -- CONDITION MEMBERS --

        /// <summary>
        /// Choose member
        /// </summary>
        private void ChooseMember()
        {
            try
            {
                if (dgvGroupList.DataSource == null)
                    return;

                // Choose leader
                for (var i = 0; i < dgvGroupList.RowCount; i++)
                {
                    var groupstudent = new GroupStudent
                    {
                       IdGroup = Convert.ToInt32(dgvGroupList.Rows[i].Cells["Id"].Value),
                       IdStudent = _students[i].Id,
                       IsLeader = true
                    };

                    string message;

                    if (_business.AddGroupStudentValidator(groupstudent, out message))
                        _business.AddGroupStudent(groupstudent);

                    else
                        MessageBox.Show(message);
                }

                // Choose member
                var remainingMembers = _students.Count - dgvGroupList.RowCount;
                var round = 1;
                if (remainingMembers < 0)
                    return;

                while (remainingMembers > 0)
                {
                    if (round % 2 == 1)
                    {
                        for (var i = 0; i < dgvGroupList.RowCount; i++)
                        {
                            var groupstudent = new GroupStudent
                                                   {
                                                       IdGroup = Convert.ToInt32(dgvGroupList.Rows[dgvGroupList.RowCount - i - 1].Cells["Id"].Value),
                                                       IdStudent = _students[i + dgvGroupList.RowCount * round].Id,
                                                       IsChecked = false
                                                   };

                            string message;

                            if (_business.AddGroupStudentValidator(groupstudent, out message))
                            {
                                _business.AddGroupStudent(groupstudent);
                                remainingMembers--;
                            }

                            else
                            {
                                MessageBox.Show(message);
                                break;
                            }
                        }
                        round++;
                    }

                    else
                    {
                        // Round 2
                        for (var i = 0; i < dgvGroupList.RowCount; i++)
                        {
                            var groupstudent = new GroupStudent
                            {
                                IdGroup = Convert.ToInt32(dgvGroupList.Rows[i].Cells["Id"].Value),
                                IdStudent = _students[i + dgvGroupList.RowCount * round].Id,
                                IsChecked = false
                            };

                            string message;

                            if (_business.AddGroupStudentValidator(groupstudent, out message))
                            {
                                _business.AddGroupStudent(groupstudent);
                                remainingMembers--;                            
                            }

                            else
                            {
                                MessageBox.Show(message);
                                break;
                            }
                        }
                        round++;
                    }
                }

                // Load lai data
                LoadGroupStudents();
            }
            catch (Exception ex)
            {
                Logger.Write(null, ex);
            }
           
        }
        

        #endregion

        #region -- MEMBER --

        private void LoadGroupStudents()
        {
            if (dgvGroupList.CurrentRow != null)
                dgvGroupStudent.DataSource = _business.GetListStudentByGroupId((int)dgvGroupList.CurrentRow.Cells["Id"].Value);

            if(dgvGroupStudent.DataSource == null)
                return;

            DataGridViewHelper.ShowHideColumns(dgvGroupStudent,
                                               new[] { PropertiesConstants.IsChecked, "StudentName", "StudentCode", "IsLeader", "IdStudent" });
            DataGridViewHelper.ShowIsCheck(dgvGroupStudent);
            DataGridViewHelper.ApplyCheckedAllOrUncheckAll(dgvGroupStudent, false);
            DataGridViewHelper.ChangeDgvHeaderText(dgvGroupStudent, new[] { "IsChecked", "StudentName", "StudentCode", "IsLeader" },
                                                   new[] { "Chọn", "Thành viên", "Mã sinh viên", "Nhóm trưởng" });
            LoadLeader();
        }

        private void LoadLeader()
        {
            for (var i = 0; i < dgvGroupStudent.RowCount; i++)
            {
                if ((bool) dgvGroupStudent.Rows[i].Cells["IsLeader"].Value)
                    txtLeader.Text = dgvGroupStudent.Rows[i].Cells["StudentName"].Value.ToString();
                else
                    continue;
            }
        }
        private void BtnMoveGroupClick(object sender, EventArgs e)
        {
            if (dgvGroupList.CurrentRow != null)
                cboNewGroup.DataSource = _business.GetListGroupwithoutGroup((int)dgvGroupList.CurrentRow.Cells["Id"].Value);
            cboNewGroup.DisplayMember = PropertiesConstants.Name;
            cboNewGroup.ValueMember = PropertiesConstants.Id;
        }

        private void BtnOkMoveGroupClick(object sender, EventArgs e)
        {
            try
            {
                if (dgvGroupStudent.CurrentRow != null)
                {
                    var group = new GroupStudent
                    {
                        Id = Convert.ToInt32(dgvGroupStudent.CurrentRow.Cells[PropertiesConstants.Id].Value),
                        IdGroup = Convert.ToInt32(((Group)cboNewGroup.SelectedItem).Id),
                        IdStudent = Convert.ToInt32(dgvGroupStudent.CurrentRow.Cells["IdStudent"].Value),
                        IsLeader = (bool) dgvGroupStudent.CurrentRow.Cells["IsLeader"].Value
                    };
                    string message;
                    if (_business.EditGroupStudentValidator(group, out message))
                    {
                        if (!_business.EditGroupStudent(group))
                        {
                            MessageBox.Show(ConstantMessages.SaveItemNotSuccess, FileConstants.ProgramName);
                            return;
                        }
                        LoadGroupStudents();                       
                    }
                    else
                        MessageBox.Show(message);
                }
                else
                    MessageBox.Show(ConstantMessages.NoSelected, FileConstants.ProgramName);
            }

            catch (Exception ex)
            {
                Logger.Write(null, ex);
            }
        }

        private void DgvGroupStudentCellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvGroupStudent == null ||
               dgvGroupStudent.Columns[(string)typeof(GroupStudent).Properties().IsChecked] == null ||
               dgvGroupStudent.Columns[(string)typeof(GroupStudent).Properties().IsChecked].Index != e.ColumnIndex)
                return;

            dgvGroupStudent[e.ColumnIndex, e.RowIndex].Value =
                !(bool)dgvGroupStudent[e.ColumnIndex, e.RowIndex].Value;
        }         

        #endregion      
    }
}
